package com.example.webflux.demo;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

public class LongPollingClient {

    {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = loggerContext.getLogger("root");
        logger.setLevel(Level.OFF);
    }
    public static void main(String[] args) {
        final RestTemplate restTemplate = getRestTemplate(15000);
        final String host = "localhost:8080";


        String data;

        ResponseEntity<String> entity = restTemplate.getForEntity("http://" + host + "/get?timeout=0", String.class);
        data = entity.getBody();
        System.out.println("首次读取配置为：" + entity.getBody());

        while (!Thread.currentThread().isInterrupted()) {
            ResponseEntity<String> result = restTemplate.getForEntity("http://" + host + "/get?timeout=14500", String.class);
            String resultBody = result.getBody();
            if (!"timeout".equalsIgnoreCase(resultBody) || !Objects.equals(data, resultBody)) {
                data = resultBody;
                System.out.println("配置更新为：" + data);
            }
        }
    }

    private static RestTemplate getRestTemplate(@SuppressWarnings("SameParameterValue") int timeout) {

        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setReadTimeout(timeout);
        return new RestTemplate(requestFactory);
    }
}
